//
//  MyGroupVC.swift
//  YueChat
//
//  Created by IMac on 2024/9/21.
//

import UIKit

class MyGroupVC: BaseVC {
    

//    override func viewWillAppear(_ animated: Bool) {
//        super.viewWillAppear(animated)
//        navigationController?.setNavigationBarHidden(true, animated: animated)
//        
//    }
//
//    override func viewWillDisappear(_ animated: Bool) {
//        super.viewWillDisappear(animated)
//        navigationController?.setNavigationBarHidden(false, animated: animated)
//    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.title = "群聊"
        
        tableStytle = .plain
        tableView.separatorInset = UIEdgeInsets(top: 0, left: 76, bottom: 0, right: 0)
        
        registerCell(withNibName: String(describing: UserCell.self), isTableView: true)
        
        let head = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(getListData))
        head.lastUpdatedTimeLabel?.isHidden = true
        head.stateLabel?.isHidden = true
        self.tableView.mj_header = head

        getData()
    }
    
    @objc func getListData () {
        let delayInSeconds = 1
        DispatchQueue.main.asyncAfter(deadline: .now() + Double(delayInSeconds)) {
            self.tableView.mj_header?.endRefreshing()
        }
        
        var ids = gosnGroup.listGroupInfo(isFav: true)//DMCCIMService.getInstance().getFavGroupsFromRemote()
        
        Task {
            let (idsFromAPI,err) = await ghttpService.listGroup()//APIManager.shared.requestMyGroup()
            
            await MainActor.run {
                if let err = err {
                    MHAlert.showMessage("\(err.description)")
                }else{
                    if idsFromAPI!.count > 0 {
                        // 处理数据
                        idsFromAPI!.forEach { dic in  
                            let groupId = dic["groupOsnId"] as? String
                            _ = gosnGroup.setGroupFav(groupId!, true)
                            getGroupInfo(groupId: groupId!)
                        }
                        
                        ids = gosnGroup.listGroupInfo(isFav: true)//DMCCIMService.getInstance().getFavGroups()
                        
                        dataSource.removeAll()
                        ids.forEach { group in
                            //DMCCIMService.getInstance().updateGroupFavDB(groupId, fav: true)
                            _ = gosnGroup.setGroupFav(group.groupId, true)
                            getGroupInfo(groupId: group.groupId)
                        }
                        
                        if dataSource.count == 0 {
                            self.view.insertSubview(self.nullView, aboveSubview: self.view)
                        } else {
                            self.nullView.removeFromSuperview()
                        }
                        
                        tableView.reloadData()
                        
                    } else {
                        // 网络错误
                    }
                    
                    if dataSource.count == 0 {
                        self.view.insertSubview(self.nullView, aboveSubview: self.view)
                    } else {
                        self.nullView.removeFromSuperview()
                    }
                    
                    tableView.reloadData()
                }
            }
            
        }
        
        
        
    }
    


    private func getGroupInfo(groupId: String) {
        let group = gosnGroup.getGroupInfoDefault(groupId)
        dataSource.append(group)
    }
    
    override func getData() {
        
        dataSource = gosnGroup.listGroupInfo(isFav: true)//DMCCIMService.getInstance().getFavGroups()!
//        for group in array {
//            let group = gosnGroup.getGroupInfo(group.groupId)!
//            dataSource.append(group)
//        }
        
        if dataSource.isEmpty {
            self.getListData()
            self.view.insertSubview(self.nullView, aboveSubview: self.view)
        } else {
            self.nullView.removeFromSuperview()
        }
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return dataSource.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: UserCell.self)) as? UserCell else { return UITableViewCell() }
        cell.setGroup(group: dataSource[indexPath.row] as! DMCCGroup)
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
//1.fw
        let group = self.dataSource[indexPath.row] as! DMCCGroup
        let info = gosnConversation.initParam(group.groupId)
        self.navigationController?.pushViewController(ChatVC(conversation: info), animated: true)
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 60
    }

}
